# **********************OBJ INFO**************************
# Author:YuKalix
# @Time    : 2021-5-7 19:19
# @Site    : 52ziyu.cn
# @File    : run_web.py
# @software: PyCharm
# *********************************************************
from flask import Flask, render_template, request
# from camera import Camera
from TCP import TCP
from CarOperation import CarOperation

class Settings:
    TargetAddress = "192.168.99.151"
    TargetPort = 9999




myTCPClient = TCP(Settings.TargetAddress, Settings.TargetPort)
myRaspberryCar = CarOperation()
# from car_server.server import OperationCar
# myCarOperation = OperationCar()
app = Flask(__name__)

@app.route('/')
def operation_page():
    myTCPClient.init_client()
    return render_template("operation_page.html")

@app.route("/car_operation")
def car_operation():
    cmd: str = request.args['cmd'].lower()
    if cmd == "f":
        myRaspberryCar.Motor_Forward()
    elif cmd == "b":
        myRaspberryCar.Motor_Backward()
    elif cmd == "l":
        myRaspberryCar.Motor_TurnLeft()
    elif cmd == "r":
        myRaspberryCar.Motor_TurnRight()
    else:
        myRaspberryCar.Motor_Stop()
    return None

@app.route("/camera/operation")
def camera_operation():
    cmd = request.args['cmd'].lower()
    print(cmd)
    if cmd == "cu":
        myRaspberryCar.SetServoAngle(8, 75)
    elif cmd == "cd":
        myRaspberryCar.SetServoAngle(8, 30)
    elif cmd == "cl":
        myRaspberryCar.SetServoAngle(7,135)
    elif cmd == "cr":
        myRaspberryCar.SetServoAngle(7, 45)
    elif cmd == 'rest':
        myRaspberryCar.SetServoAngle(7, 90)
        myRaspberryCar.SetServoAngle(8, 30)

    else:
        return "No"

    return None


G_Flag = 1
@app.route("/auto_obstacle_avoidance")
def auto_obstacle_avoidance():
    global G_Flag
    G_Flag = 1
    while True:
        if G_Flag:
            myRaspberryCar.Avoid_wave()
        else:
            myRaspberryCar.Motor_Stop()
            break

@app.route("/estop_car")
def estop_car():
    global G_Flag
    G_Flag = 0
    return render_template("operation_page.html")

@app.route("/get_cpu_temperature")
def temperature():
    temperature_ = myRaspberryCar.cpu_temp()
    return str(temperature_)

@app.route("/get_ranging")
def ranging():
    tmp_ranging = int(myRaspberryCar.Get_Distence())
    return str(tmp_ranging)


@app.route("/test")
def test():
    for i in range(5):
        print(i)
        myRaspberryCar.SetServoAngle(i, 30)

if __name__ == '__main__':
   app.run(host="0.0.0.0", port=9998)
   # app.run()